<template>
  <div class="custom-content-management">
    <el-card>
      <!-- 页面头部 -->
      <template #header>
        <div class="card-header">
          <span>自定义行程内容管理</span>
        </div>
      </template>

      <div class="page-content">
        <!-- 平台选择和工具栏 -->
        <el-card class="toolbar-card" shadow="never">
          <div class="toolbar">
            <div class="platform-selector">
              <el-radio-group v-model="activePlatform" @change="handlePlatformChange" size="large">
                <el-radio-button label="ctrip">
                  <el-icon>
                    <Shop/>
                  </el-icon>
                  携程
                </el-radio-button>
<!--                              <el-radio-button label="tongcheng">-->
<!--                                <el-icon><Location /></el-icon>-->
<!--                                同程-->
<!--                              </el-radio-button>-->
<!--                              <el-radio-button label="mafengwo">-->
<!--                                <el-icon><Guide /></el-icon>-->
<!--                                马蜂窝-->
<!--                              </el-radio-button>-->
              </el-radio-group>
            </div>

            <div class="toolbar-actions">
              <el-button @click="refreshData" type="primary" :loading="refreshing">
                <el-icon>
                  <Refresh/>
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 快速操作面板 -->
        <el-card class="quick-actions-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Lightning/>
              </el-icon>
              <span>快速操作</span>
            </div>
          </template>

          <div class="quick-actions">
            <el-button-group>
              <el-button @click="openCreateDialog('first_day')" type="primary" plain>
                <el-icon>
                  <Plus/>
                </el-icon>
                创建第一天模板
              </el-button>
              <el-button @click="openCreateDialog('last_day')" type="warning" plain>
                <el-icon>
                  <Plus/>
                </el-icon>
                创建最后一天模板
              </el-button>
            </el-button-group>

            <el-button @click="openCreateDialog()" type="success" plain>
              <el-icon>
                <Plus/>
              </el-icon>
              创建新内容
            </el-button>
          </div>
        </el-card>

        <!-- 内容列表 -->
        <el-card class="list-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon>
                  <List/>
                </el-icon>
                <span>{{ platformLabels[activePlatform] }} 内容列表</span>
                <el-badge :value="contentList.ctrip.length" class="item-count"/>
              </div>
            </div>
          </template>

          <el-table
              :data="filteredContentList"
              v-loading="listLoading"
              stripe
              style="width: 100%"
          >
            <el-table-column type="selection" width="55"/>

            <el-table-column prop="dayType" label="类型" width="120" sortable>
              <template #default="{ row }">
                <el-tag
                    :type="row.dayType === 'first_day' ? 'success' : 'warning'"
                    effect="light"
                >
                  <el-icon>
                    <component :is="row.dayType === 'first_day' ? 'Sunrise' : 'Sunset'"/>
                  </el-icon>
                  {{ row.dayType === 'first_day' ? '第一天' : '最后一天' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip sortable/>

            <el-table-column label="适用范围" min-width="50">
              <template #default="{ row }">
                <div class="scope-info">
                  <div v-if="row.departureCity || row.destinationCity" class="city-info">
                    <el-tag size="small" type="info" effect="plain">
                      <el-icon>
                        <Location/>
                      </el-icon>
                      {{ row.departureCity || '任意' }} → {{ row.destinationCity || '任意' }}
                    </el-tag>
                  </div>
                  <div v-if="row.durationDays" class="duration-info">
                    <el-tag size="small" type="primary" effect="plain">
                      <el-icon>
                        <Calendar/>
                      </el-icon>
                      {{ row.durationDays }}天
                    </el-tag>
                  </div>
                  <div v-if="!row.departureCity && !row.destinationCity && !row.durationDays">
                    <el-tag size="small" type="success" effect="light">
                      <el-icon>
                        <Star/>
                      </el-icon>
                      通用模板
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="enabled" label="状态" width="80" sortable>
              <template #default="{ row }">
                <el-switch
                    v-model="row.enabled"
                    @change="toggleContentStatus(row)"
                    :loading="row.toggling"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                />
              </template>
            </el-table-column>

            <el-table-column prop="updateTime" label="更新时间" width="160" sortable>
              <template #default="{ row }">
                <div class="time-info">
                  <el-icon>
                    <Clock/>
                  </el-icon>
                  {{ formatTime(row.updateTime) }}
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button-group size="small">
                  <el-button @click="openEditDialog(row)" type="primary" plain>
                    <el-icon>
                      <Edit/>
                    </el-icon>
                    编辑
                  </el-button>
                  <el-button @click="previewContent(row)" type="info" plain>
                    <el-icon>
                      <View/>
                    </el-icon>
                    预览
                  </el-button>
                  <el-button @click="duplicateContent(row)" type="success" plain>
                    <el-icon>
                      <DocumentCopy/>
                    </el-icon>
                    复制
                  </el-button>
                  <el-popconfirm
                      title="确定要删除这个内容吗？"
                      @confirm="deleteContent(row.id)"
                      width="200"
                  >
                    <template #reference>
                      <el-button type="danger" plain>
                        <el-icon>
                          <Delete/>
                        </el-icon>
                      </el-button>
                    </template>
                  </el-popconfirm>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-card>

    <!-- 内容编辑弹窗 -->
    <ContentEditorDialog
        ref="editorDialogRef"
        v-model="editorDialogVisible"
        :edit-data="currentEditData"
        :platform="activePlatform"
        @submit="handleContentSubmit"
        @close="handleEditorClose"
    />

    <!-- 预览对话框 -->
    <el-dialog
        v-model="previewVisible"
        title="内容预览"
        width="80%"
        class="preview-dialog"
        :before-close="handlePreviewClose"
    >
      <div class="preview-toolbar">
        <el-radio-group v-model="previewMode" size="small">
          <el-radio-button label="table">表格视图</el-radio-button>
          <el-radio-button label="html">HTML源码</el-radio-button>
        </el-radio-group>
      </div>

      <div class="preview-content" :class="previewMode">
        <div v-if="previewMode === 'table'" v-html="previewHtml"></div>
        <pre v-else><code>{{ previewHtml }}</code></pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Shop, Location, Refresh, Lightning, Plus,
  Edit, List, Calendar, Star, Delete, Clock, View, DocumentCopy, Guide
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { customContentApi } from "@/api/customContent.js"
import ContentEditorDialog from '@/components/ContentEditorDialog.vue' // 导入弹窗组件

// 响应式数据
const activePlatform = ref('ctrip')
const listLoading = ref(false)
const refreshing = ref(false)
const contentList = ref({
  ctrip: [],
  tongcheng: [],
  mafengwo: []
})

// 搜索和筛选
const searchKeyword = ref('')
const filterDayType = ref('')

// 预览相关
const previewVisible = ref(false)
const previewHtml = ref('')
const previewMode = ref('table')

// 编辑器弹窗相关
const editorDialogVisible = ref(false)
const currentEditData = ref(null)
const editorDialogRef = ref() // 添加弹窗组件引用

// 平台标签
const platformLabels = {
  ctrip: '携程',
  tongcheng: '同程',
  mafengwo: '马蜂窝'
}

// 计算属性 - 过滤后的内容列表
const filteredContentList = computed(() => {
  let list = contentList.value[activePlatform.value] || []

  // 按关键词搜索
  if (searchKeyword.value) {
    list = list.filter(item =>
        item.title.includes(searchKeyword.value) ||
        item.departureCity?.includes(searchKeyword.value) ||
        item.destinationCity?.includes(searchKeyword.value)
    )
  }

  // 按天数类型筛选
  if (filterDayType.value) {
    list = list.filter(item => item.dayType === filterDayType.value)
  }

  return list
})

// 生命周期
onMounted(() => {
  loadPlatformContents()
})

// 方法
const loadPlatformContents = async () => {
  listLoading.value = true
  try {
    const response = await customContentApi.getAllPlatformContents()
    if (response.code === 200) {
      contentList.value = response.data
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误：' + error.message)
  } finally {
    listLoading.value = false
  }
}

const refreshData = async () => {
  refreshing.value = true
  try {
    await loadPlatformContents()
    ElMessage.success('刷新成功')
  } finally {
    refreshing.value = false
  }
}

const handlePlatformChange = () => {
  // 平台切换时重新加载数据
  loadPlatformContents()
}

// 打开创建对话框
const openCreateDialog = (dayType = '') => {
  currentEditData.value = null
  if (editorDialogRef.value) {
    editorDialogRef.value.openDialog(dayType, null)
  }
}

// 打开编辑对话框
const openEditDialog = (row) => {
  currentEditData.value = { ...row }
  if (editorDialogRef.value) {
    editorDialogRef.value.openDialog('', row)
  }
}

// 复制内容
const duplicateContent = (row) => {
  const newContent = { ...row }
  delete newContent.id
  newContent.title = `${newContent.title} - 副本`
  newContent.enabled = false

  if (editorDialogRef.value) {
    editorDialogRef.value.openDialog('', newContent)
  }
  ElMessage.success('内容已复制，请修改后保存')
}

// 处理内容提交
const handleContentSubmit = async (formData) => {
  try {
    const response = await customContentApi.saveOrUpdateContent(formData)
    if (response.code === 200) {
      ElMessage.success(formData.id ? '更新成功' : '保存成功')
      editorDialogVisible.value = false
      loadPlatformContents()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message)
  }
}

// 处理编辑器关闭
const handleEditorClose = () => {
  currentEditData.value = null
  editorDialogVisible.value = false
}

// 切换内容状态
const toggleContentStatus = async (row) => {
  row.toggling = true
  try {
    const response = await customContentApi.toggleContent(row.id)
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      row.enabled = !row.enabled
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    row.enabled = !row.enabled
    ElMessage.error('网络错误：' + error.message)
  } finally {
    row.toggling = false
  }
}

// 删除内容
const deleteContent = async (id) => {
  try {
    const response = await customContentApi.deleteContent(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadPlatformContents()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    ElMessage.error('网络错误：' + error.message)
  }
}

// 预览内容
const previewContent = (row) => {
  const content = row.content

  if (!content || content.trim() === '<table class="print_table"><tbody></tbody></table>') {
    ElMessage.warning('内容为空或表格中无数据')
    return
  }

  previewHtml.value = `
    <div style="font-family: Arial, sans-serif; padding: 20px; background-color: #fff;">
      <h3 style="color: #409eff; border-bottom: 2px solid #409eff; padding-bottom: 10px;">
        ${row.title || '预览'}
      </h3>
      <div class="preview-body">
        ${content}
      </div>
    </div>
  `
  previewVisible.value = true
}

// 关闭预览
const handlePreviewClose = () => {
  previewVisible.value = false
  previewMode.value = 'table'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('MM-DD HH:mm')
}
</script>

<style scoped>
.custom-content-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .page-content {
    background: white;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 6px 25px rgba(0, 0, 0, 0.06);
  }

  .toolbar-card {
    margin-bottom: 25px;
    border-radius: 12px;
    border: none;
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
  }

  .toolbar-actions {
    display: flex;
    gap: 10px;
  }

  .quick-actions-card {
    margin-bottom: 25px;
    border-radius: 12px;
    border: none;
  }

  .quick-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
  }

  .list-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .item-count {
    margin-left: 5px;
  }

  .scope-info {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .city-info, .duration-info {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .time-info {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 13px;
    color: #606266;
  }

  .preview-dialog {
    border-radius: 12px;
  }

  .preview-toolbar {
    margin-bottom: 20px;
    text-align: center;
  }

  .preview-content {
    max-height: 70vh;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 8px;
  }

  .preview-content.table {
    padding: 20px;
    background: #fafbfc;
  }

  .preview-content pre {
    margin: 0;
    padding: 20px;
    background: #f6f8fa;
    color: #24292e;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 13px;
    line-height: 1.5;
  }
}

/* 预览样式增强 */
:deep(.preview-body .print_table) {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.preview-body .print_table th),
:deep(.preview-body .print_table td) {
  border: 1px solid #e4e7ed;
  padding: 12px 16px;
  text-align: left;
  vertical-align: top;
  line-height: 1.6;
}

:deep(.preview-body .print_table_time) {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
  margin: 0 0 5px 0;
}

:deep(.preview-body .print_table_title) {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
  margin: 0 0 10px 0;
  padding: 6px 12px;
  background-color: #f0f9ff;
  border-left: 4px solid #409eff;
  border-radius: 4px;
}
</style>